using System;
using System.Collections.Specialized;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Extensions.Hosting;

using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;

namespace Fulu.TSC.WebDemo
{
    public class BackgroundServiceDemo : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            NameValueCollection properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = $"Hos.ScheduleMaster:{Environment.MachineName}";
            properties["quartz.scheduler.instanceId"] = $"Hos.ScheduleMaster:{Environment.MachineName}";
            properties["quartz.scheduler.makeSchedulerThreadDaemon"] = "true";
            properties["quartz.serializer.type"] = "binary";
            int maxConcurrency = 5;
            if (maxConcurrency > 0)
            {
                properties["quartz.threadPool.maxConcurrency"] = maxConcurrency.ToString();
            }

            ISchedulerFactory factory = new StdSchedulerFactory(properties);
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

            string jobKey = Guid.NewGuid().ToString();
            JobDataMap map = new JobDataMap();
            IJobDetail job = JobBuilder.Create().OfType(typeof(TestJob)).WithIdentity(jobKey).UsingJobData(map).Build();
            ITrigger trigger = new CronTriggerImpl
            {
                //CronExpressionString = "0 0/1 * * * ? ",
                CronExpressionString = "0/3 * * * * ? ",
                Name = "任务标题",
                Key = new TriggerKey(jobKey),
                Description = "测试描述",
                MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing,
                JobKey = new JobKey(jobKey),
            };

            await scheduler.ScheduleJob(job, trigger, stoppingToken);
        }
    }
}
